cmake_minimum_required(VERSION 3.5)

project(fiona LANGUAGES Fortran)

if (CMAKE_Fortran_COMPILER_ID MATCHES Intel)
  set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -no-wrap-margin -Ofast")
  if (CMAKE_BUILD_TYPE MATCHES Debug)
    set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -g -traceback")
  endif ()
elseif (CMAKE_Fortran_COMPILER_ID MATCHES GNU)
  if (APPLE)
    set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -ffree-line-length-none")
  else ()
    set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -ffree-line-length-none")
  endif ()
  if (CMAKE_BUILD_TYPE MATCHES Debug)
    set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -g -gdwarf -Og -fbacktrace -fcheck=all")
  endif ()
endif ()
set(CMAKE_Fortran_MODULE_DIRECTORY "${CMAKE_BINARY_DIR}")

get_filename_component(CMAKE_Fortran_COMPILER_NAME ${CMAKE_Fortran_COMPILER} NAME)
if (CMAKE_Fortran_COMPILER_NAME MATCHES "mpi")
  find_package(MPI)
  if (MPI_Fortran_FOUND)
    add_definitions(-DHAS_MPI)
  endif ()
endif ()

if (DEFINED ENV{NETCDF} AND (NOT DEFINED ENV{NETCDF_ROOT}))
  set(ENV{NETCDF_ROOT} $ENV{NETCDF})
endif ()
if (DEFINED ENV{NETCDF_ROOT})
  set(NETCDF_INCLUDEDIR "$ENV{NETCDF_ROOT}/include")
  set(NETCDF_LIBDIR "$ENV{NETCDF_ROOT}/lib")
else ()
  find_package(PkgConfig)
  if (PKG_CONFIG_FOUND)
    pkg_search_module(NETCDF REQUIRED netcdf)
  else ()
    message(FATAL_ERROR "Unable to find pkg-config library!")
  endif ()
endif ()

# Check if netCDF library supports parallel IO.
execute_process(
  COMMAND "nc-config" "--has-parallel4"
  OUTPUT_VARIABLE res
)
if (res MATCHES "no")
  message("Disable parallel IO due to incapability of netCDF library.")
  add_definitions(-DNO_PARALLEL)
endif ()

get_directory_property(parent_dir PARENT_DIRECTORY)
if (EXISTS ${PROJECT_SOURCE_DIR}/lib/container/CMakeLists.txt AND NOT parent_dir)
  add_subdirectory(lib/container)
endif ()
if (EXISTS ${PROJECT_SOURCE_DIR}/lib/flogger/CMakeLists.txt AND NOT parent_dir)
  add_subdirectory(lib/flogger)
endif ()
if (EXISTS ${PROJECT_SOURCE_DIR}/lib/string/CMakeLists.txt AND NOT parent_dir)
  add_subdirectory(lib/string)
endif ()
if (EXISTS ${PROJECT_SOURCE_DIR}/lib/unit-test/CMakeLists.txt AND NOT parent_dir)
  add_subdirectory(lib/unit-test)
endif ()

set(sources
  src/fiona_common_mod.F90
  src/fiona_buffer_mod.F90
  src/fiona_dim_mod.F90
  src/fiona_var_mod.F90
  src/fiona_dataset_mod.F90
  src/fiona_objects_mod.F90
  src/fiona_input_mod.F90
  src/fiona_output_mod.F90
  src/fiona_mod.F90
  src/fiona.F90
)

add_library(fiona ${sources})
target_include_directories(fiona PUBLIC ${NETCDF_INCLUDEDIR})
if (${CMAKE_VERSION} VERSION_GREATER "3.13")
  target_link_directories(fiona PUBLIC ${NETCDF_LIBDIR})
endif ()
target_link_libraries(fiona netcdf netcdff fortran_container flogger fortran_string)

if (NOT parent_dir)
  add_executable(fiona_test.exe src/fiona_test.F90)
  target_link_libraries(fiona_test.exe fiona fortran_unit_test)
endif ()
